package com.atguigu.bigdata.chapter05.transform;

import com.atguigu.bigdata.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2022/9/2 10:26
 */
public class Flink13_Process_NoKey {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        // 统计每个传感器的水位和
        env
            .readTextFile("input/sensor.txt")
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(
                        data[0],
                        Long.valueOf(data[1]),
                        Integer.valueOf(data[2])
                    );
                }
            })
            .process(new ProcessFunction<WaterSensor, String>() {
    
                private ValueState<String> a;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    a = getRuntimeContext().getState(new ValueStateDescriptor<String>("a", String.class));
                }
    
                // 处理流中的数据
                // 参数1: 就是要处理的元素
                // 参数2: 上下文对象
                // 参数3: 输出数据
                int sum = 0;  // 状态
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    a.value();
                    sum += value.getVc();
                    
                    out.collect("水位和: " + sum);
                }
            })
            .print();
            
           
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*

 
 
 */